package com.mine.spring.servlet;

import com.mine.spring.entity.Result;
import com.mine.spring.factory.BeanFactory;
import com.mine.spring.factory.ProxyFactory;
import com.mine.spring.service.TransferService;
import com.mine.spring.utils.JsonUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;

@WebServlet(urlPatterns = "/transferServlet")
public class TestServlet extends HttpServlet {

    //v1 所有实现均手动创建
    //v1 每次访问都是获取了一个新连接，无法控制事务

    //private TransferService transferService = new TransferServiceImpl();
    // v2 通过工厂回去
    //private TransferService transferService = (TransferService) BeanFactory.getBean("transferService");

    // v3 从工厂获取委托对象（委托对象是增强了事务控制的功能）,transferService增强功能
    private ProxyFactory proxyFactory = (ProxyFactory) BeanFactory.getBean("proxyFactory");

    //jdk 动态代理
    private TransferService transferService = (TransferService) proxyFactory.getJdkProxy(BeanFactory.getBean("transferService"));


    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        System.out.println("开始处理");
        // 设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {
            // 2. 调用service层方法
            //transferService.transfer(fromCardNo,toCardNo,money);

            // mybatis 实现
            transferService.transfer2(fromCardNo,toCardNo,money);
            result.setStatus("200");
            System.out.println("=============转账成功============");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }


}
